package com.aidex.web.controller.api;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.bo.WxOauth2;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.AliyunUtils;
import com.aidex.biz.utils.DictanceUtil;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.file.FileUploadUtils;
import com.aidex.framework.cache.DictUtils;
import com.aidex.framework.config.ServerConfig;
import com.aidex.system.domain.SysDictData;
import com.aidex.system.domain.SysNotice;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.SysDictDataService;
import com.aidex.system.service.SysNoticeService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.PageInfo;
import com.lop.open.api.sdk.LopException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小程序用户业务接口
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-09-21
 */
@RestController("ApiUserInfoController")
@RequestMapping("/api/userInfo")
@Api(tags = "小程序用户业务接口")
@Component
public class UserInfoController extends BaseController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private EquInfoService equInfoService;
    @Autowired
    private RubbishTypeService rubbishTypeService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private WeChatLoginService weChatLoginService;
    @Autowired
    private ShoppingCarService shoppingCarService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private SysNoticeService sysNoticeService;
    @Autowired
    private AccountInfoService accountInfoService;

    @Autowired
    private FriendsLinksService friendsLinksService;

    @Autowired
    private UserTixianService userTixianService;
    @Autowired
    private AccountLogService accountLogService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private LbsMapService lbsMapService;
    @Autowired
    private AppointmentCompanyService appointmentCompanyService;

    @Autowired
    private CouponInfoService couponInfoService;

    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private WxPayService wxPayService;


    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private SongsInfoService songsInfoService;

    @Autowired
    private UserSongsTicketService userSongsTicketService;

    @Autowired
    private OrderImageService orderImageService;

    @Autowired
    private RefundOrderService refundOrderService;

    @Autowired
    private JdKuaiyunService jdKuaiyunService;

    @Autowired
    private SysDictDataService sysDictDataService;


    /**
     * 小程序用户授权获取openId
     *
     * @param code
     * @param companyId
     * @return
     */
    @GetMapping("/getOpenId")
    public R getOpenId(@RequestParam String code, @RequestHeader(name = "company-id") String companyId) {

        Company company = companyService.get(companyId);
        if (null == company) {
            return R.fail("商户不存在");
        }
        weChatLoginService.setAppId(company.getWechatXappid(), company.getWechatXappSecret());
        return R.data(weChatLoginService.getOpenId(code));
    }

    /**
     * 小程序获取用户手机号
     *
     * @param code
     * @param openid
     * @param companyId
     * @return
     */
    @GetMapping("/getPhoneNumber")
    public R getPhoneNumber(@RequestParam String code, String openid,
            @RequestHeader(name = "company-id") String companyId) {
        Company company = companyService.get(companyId);
        if (null == company) {
            return R.fail("商户不存在");
        }
        weChatLoginService.setAppId(company.getWechatXappid(), company.getWechatXappSecret());
        if (StringUtils.isNull(openid)) {
            return R.fail("参数openid为空");
        }
        String phone = weChatLoginService.getphoneNumber(code);
        if (StringUtils.isNull(phone)) {
            return R.fail("手机获取失败");
        }
        // 根据openid 查询信息
        UserInfo userInfo = userInfoService.get(openid);
        if (null != userInfo) {
            userInfo.setNikeName("wx" + phone);
            userInfo.setPhone(phone);
            userInfoService.save(userInfo);
        }

        return R.data(userInfo);
    }

    /**
     * 小程序用户登录
     *
     * @param userInfo
     * @param companyId
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UserInfo userInfo, @RequestHeader(name = "company-id") String companyId) {
        Company company = companyService.get(companyId);
        if (null == company) {
            return R.fail("商户不存在");
        }
        userInfo.setCompanyId(companyId);
        weChatLoginService.setAppId(company.getWechatXappid(), company.getWechatXappSecret());
        return R.data(weChatLoginService.login(userInfo));
    }


    /**
     * 更新用户信息
     *
     * @param userInfo
     * @param companyId
     * @return
     */
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody UserInfo userInfo, @RequestHeader(name = "company-id") String companyId) {
        // Company company = companyService.get(companyId);

        try{
            UserInfo us = userInfoService.get(userInfo.getUserInfoId());
            if (!StringUtils.isEmpty(userInfo.getName())) {
                us.setIsShiming(1);
                us.setName(userInfo.getName());
            }
            if (!StringUtils.isEmpty(userInfo.getAvatar())) {
                us.setAvatar(userInfo.getAvatar());
            }
            if (!StringUtils.isEmpty(userInfo.getPhone())) {
                us.setPhone(userInfo.getPhone());
            }
            if (!StringUtils.isEmpty(userInfo.getNikeName())) {
                us.setIsShiming(1);
                us.setNikeName(userInfo.getNikeName());
            }
            if (!StringUtils.isEmpty(userInfo.getIdCard())) {
                us.setIdCard(userInfo.getIdCard());
            }

            if (userInfoService.save(us)) {
                return R.data(userInfoService.get(userInfo.getUserInfoId()), "更新用户成功");
            } else {
                return R.fail("更新用户失败");
            }
        }catch (Exception exception){
            logger.error("用户更新",exception.getMessage());
            return R.fail("更新用户失败");
        }
    }

    /**
     * 获取用户信息
     *
     * @param userInfoId 用户ID
     * @return
     */
    @GetMapping("/getUserInfo")
    public R getUserInfo(@RequestParam String userInfoId) {
        if (!StringUtils.isEmpty(userInfoId)) {
            return R.data(userInfoService.get(userInfoId));
        } else {
            return R.fail("userInfoId is null");
        }

    }


    /**
     * 获取洗护或者商城分类信息
     *
     * @param level
     * @param id
     * @param busType 0 洗护 1 商城
     * @return 结果
     */
    @GetMapping("/getRubbishType")
    public R<List<RubbishType>> getRubbishType(@RequestParam int level, String id, Integer busType, String companyId) {
        if (level == 0) {
            level = 2;
        }
        RubbishType sysRubbishType = new RubbishType();
        sysRubbishType.setCompanyId(companyId);
        sysRubbishType.setBusType(busType);
        List<RubbishType> depts = rubbishTypeService.listDataByLevel(sysRubbishType, level, id);
        return R.data(depts);
    }


    /**
     * 获取用户地址列表信息
     *
     * @param userAddress 地址信息
     * @return 结果
     */
    @GetMapping("/getUserAddressInfo")
    public R getUserAddressInfo(UserAddress userAddress, HttpServletRequest request, HttpServletResponse response) {
        if (null == userAddress.getUserInfoId()) {
            PageInfo pageInfo = new PageInfo();
            return R.data(pageInfo);
        }
        userAddress.setPage(new PageDomain(request, response));
        return R.data(userAddressService.findPage(userAddress));
    }

    /**
     * 添加、修改用户（默认）地址信息
     *
     * @param userAddress 地址信息
     * @return 结果
     */
    @PostMapping("/addUserAddressInfo")
    public R addUserAddressInfo(@RequestBody UserAddress userAddress) {
        if ("1".equals(userAddress.getStatus())) {
            // 如果当前设置的是默认的则先处理其他地址为不默认
            userAddressService.updateStatusByStatus(userAddress);
        } else {
            if (userAddressService.findListByUserInfoId(userAddress).size() == 0) {
                userAddress.setStatus("1");
            }
        }
        return R.data(userAddressService.save(userAddress));
    }

    /**
     * 修改用户地址信息
     *
     * @param userAddress 地址信息
     * @return 结果
     */
    @PostMapping("/editUserAddressInfo")
    public R editUserAddressInfo(@RequestBody UserAddress userAddress) {
        if ("1".equals(userAddress.getStatus())) {
            // 如果当前设置的是默认的则先处理其他地址为不默认
            userAddressService.updateStatusByStatus(userAddress);
        }
        return R.data(userAddressService.save(userAddress));
    }

    /**
     * 删除用户地址信息
     *
     * @param id 地址ID
     * @return 结果
     */
    @GetMapping("/delUserAddressInfo")
    public R delUserAddressInfo(@RequestParam String id) {

        return R.data(userAddressService.deleteUserAddressByIds(new String[]{id}));
    }

    /**
     * 获取用户地址详情信息
     *
     * @param id 地址ID
     * @return 结果
     */
    @GetMapping("/getUserAddressInfoDetails")
    public R getUserAddressInfoDetails(@RequestParam String id) {
        return R.data(userAddressService.get(id));
    }


    /**
     * 获取优惠券列表
     *
     * @return 结果
     */
    @GetMapping("/getCouponInfoList")
    public R<PageInfo> getCouponInfoList(CouponInfo couponInfo, HttpServletRequest request,
            HttpServletResponse response) {
        couponInfo.setPage(new PageDomain(request, response));
        return R.data(couponInfoService.findPage(couponInfo));
    }

    /**
     * 用户领取优惠券
     *
     * @param couponId   优惠券ID
     * @param userInfoId 用户ID
     * @return 结果
     */
    @GetMapping("/userGetCouponInfo")
    public R userGetCouponInfo(@RequestParam String couponId, @RequestParam String userInfoId) {
        UserCoupon userCoupon = new UserCoupon();
        if (StringUtils.isEmpty(userInfoId) || StringUtils.isEmpty(couponId)) {
            return R.fail("参数有空值");
        }

        userCoupon.setCouponId(couponId);
        userCoupon.setUserInfoId(userInfoId);
        int counts = userCouponService.findList(userCoupon).size();
        if (counts > 0) {
            return R.fail("您已经领过该券");
        }
        userCoupon.setStatus("0"); // 待使用
        userCoupon.setSort(userCouponService.findMaxSort(new UserCoupon()));
        return R.status(userCouponService.save(userCoupon));
    }

    /**
     * 查询用户领取的优惠券
     *
     * @param userCoupon 用户ID
     * @param userCoupon 状态  0待使用 1已经使用 2已过期
     * @return 结果
     */
    @GetMapping("/getUserCouponInfoList")
    public R<PageInfo> getUserCouponInfoList(UserCoupon userCoupon) {

        return R.data(userCouponService.findPage(userCoupon));
    }


    /**
     * 删除优惠券信息
     *
     * @param id 优惠券ID
     */
    @GetMapping("/deleteUserCouponInfo")
    public R deleteUserCouponInfo(@RequestParam String id) {
        return R.status(userCouponService.deleteUserCouponByIds(new String[]{id}));
    }

    /**
     * 获取优惠券信息
     *
     * @param id 优惠券ID
     */
    @GetMapping("/getUserCouponInfo")
    public R getUserCouponInfo(@RequestParam String id) {
        return R.data(userCouponService.get(id));
    }


    /**
     * 添加商品到购物车
     *
     * @param shoppingCar 购物车信息
     * @return
     */
    @PostMapping("/addProductToShoppingCar")
    public R addProductToShoppingCar(@RequestBody ShoppingCar shoppingCar) {
        List<ShoppingCar> shoppingCarList = shoppingCarService.findList(shoppingCar);
        if (shoppingCarList.size() > 0) {
            ShoppingCar oldShoppingCar = getShoppingCar(shoppingCar, shoppingCarList);
            return R.data(shoppingCarService.save(oldShoppingCar) ? oldShoppingCar.getId() : null);
        }
        shoppingCar.setId(UUID.randomUUID().toString());
        shoppingCar.setIsNewRecord();
        shoppingCar.setSort(shoppingCarService.findMaxSort(new ShoppingCar()));
        shoppingCar.setStatus("0");
        shoppingCar.setAmount(shoppingCar.getSalePrice().multiply(new BigDecimal(shoppingCar.getCount())));
        return R.data(shoppingCarService.save(shoppingCar) ? shoppingCar.getId() : null);

    }
    /**
     * 直接购买商品
     *
     * @param shoppingCar 购物车信息
     * @return
     */
    @PostMapping("/addProductToShoppingCarXiaDan")
    public R addProductToShoppingCarXiaDan(@RequestBody ShoppingCar shoppingCar) {
        shoppingCar.setId(UUID.randomUUID().toString());
        shoppingCar.setIsNewRecord();
        shoppingCar.setSort(shoppingCarService.findMaxSort(new ShoppingCar()));
        shoppingCar.setStatus("1");
        shoppingCar.setAmount(shoppingCar.getSalePrice().multiply(new BigDecimal(shoppingCar.getCount())));
        return R.data(shoppingCarService.save(shoppingCar) ? shoppingCar.getId() : null);

    }

    private static ShoppingCar getShoppingCar(ShoppingCar shoppingCar, List<ShoppingCar> shoppingCarList) {
        ShoppingCar oldShoppingCar = shoppingCarList.get(0);
        oldShoppingCar.setCount(oldShoppingCar.getCount() + shoppingCar.getCount());
        oldShoppingCar.setPrice(shoppingCar.getPrice());
        oldShoppingCar.setSalePrice(shoppingCar.getSalePrice());
        oldShoppingCar.setUnit(shoppingCar.getUnit());
        oldShoppingCar.setUpc(shoppingCar.getUpc());
        oldShoppingCar.setImage(shoppingCar.getImage());
        oldShoppingCar.setType(shoppingCar.getType());
        oldShoppingCar.setAmount(oldShoppingCar.getSalePrice().multiply(new BigDecimal(oldShoppingCar.getCount())));
        return oldShoppingCar;
    }

    /**
     * 获取购物车商品列表
     *
     * @param shoppingCar 购物车信息
     * @return
     */
    @GetMapping("/getShoppingCarList")
    public R<PageInfo<ShoppingCar>> getShoppingCarList(ShoppingCar shoppingCar) {
        return R.data(shoppingCarService.findPage(shoppingCar));
    }

    /**
     * 获取选中购物车商品列表
     *
     * @param shoppingCar 购物车信息
     * @return
     */
    @GetMapping("/getShoppingCarListByIds")
    public R<List<ShoppingCar>> getShoppingCarListByIds(ShoppingCar shoppingCar) {
        shoppingCar.setIdsArr(shoppingCar.getIds().split(","));
        if (shoppingCar.getIdsArr().length > 0) {
            return R.data(shoppingCarService.findListByIds(shoppingCar.getIdsArr()));
        } else {
            return R.fail("ids无效！");
        }

    }

    /**
     * 修改购物商品信息
     *
     * @param shoppingCar 购物车信息
     * @return
     */
    @PostMapping("/updateProductToShoppingCar")
    public R updateProductToShoppingCar(@RequestBody ShoppingCar shoppingCar,
            @RequestHeader(name = "company-id") String companyId) {

        shoppingCar.setAmount(shoppingCar.getSalePrice().multiply(new BigDecimal(shoppingCar.getCount())));
        return R.data(shoppingCarService.save(shoppingCar));
    }

    /**
     * 删除购物车商品信息
     *
     * @param id 购物车ID
     */
    @GetMapping("/deleteShoppingCarProduct")
    public R deleteShoppingCarProduct(@RequestParam String id) {
        return R.status(shoppingCarService.deleteShoppingCarByIds(new String[]{id}));
    }


    /**
     * 合作商申请(驿站合伙人)
     *
     * @param company 合作商信息
     * @return
     */
    @PostMapping("/addCompanyInfo")
    public R addCompanyInfo(@RequestBody Company company) {
        String id = StringUtils.Getnum();
        id = id.substring(9);
        company.setId(id);
        company.setIsNewRecord();
        company.setSort(companyService.findMaxSort(new Company()));
        company.setStatus("0");
        return R.data(companyService.save(company));
    }


    /**
     * 订单提交
     *
     * @param order 订单信息
     * @return
     */
    @PostMapping("/submitOrder")
    public R submitOrder(@RequestBody Order order) {
        try {
            // 1.创建订单信息  2.地址信息 3.购物车cartIds 计算订单金额  4.优惠券信息 5.保价信息
            String orderId = StringUtils.Getnum();
            order.setOrderId(orderId);
            order.setId(orderId);
            order.setIsNewRecord();
            order.setStatus("-1");
            order.setPayStatus(0);
            order.setIsBill("0");// 待入账
            order.setSort(orderService.findMaxSort(order));
            String day="";
            if("0".equals(order.getOrderType())&&"1".equals(order.getOrderInType())){
                if("toDay".equals(order.getDay())){
                    day=DateFormatUtils.format(new Date(), "yyyy-MM-dd");
                }
                if("tomorrow".equals(order.getDay())){
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_YEAR, 1);
                    day=DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd");
                    // 将日期增加1天
                    calendar.add(Calendar.DAY_OF_YEAR, 1);
                }
                if("acquired".equals(order.getDay())){
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_YEAR, 2);
                    day=DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd");
                }
                order.setVisitBeginTime(day+" "+order.getVisitBeginTime());
                order.setVisitEndTime(day+" "+order.getVisitEndTime());
            }
            String[] cartIds = order.getCartsIds().split(",");
            BigDecimal orderAmount = new BigDecimal("0.00");
            // 查询购物车
            if (cartIds.length > 0) {
                List<ShoppingCar> shoppingCarList = shoppingCarService.findListByIds(cartIds);
                for (ShoppingCar shoppingCar : shoppingCarList) {
                    OrderDetails orderDetails = new OrderDetails();
                    orderDetails.setSort(orderDetailsService.findMaxSort(orderDetails));
                    orderDetails.setOrderId(orderId);
                    orderDetails.setPrice(shoppingCar.getPrice());
                    orderDetails.setProductId(shoppingCar.getProductId());
                    orderDetails.setProductSkuId(shoppingCar.getProductSkuId());
                    orderDetails.setCount(shoppingCar.getCount());
                    orderDetails.setProductName(shoppingCar.getProductName());
                    orderDetails.setUpc(shoppingCar.getUpc());
                    orderDetails.setUnit(shoppingCar.getUnit());
                    orderDetails.setAmount(shoppingCar.getAmount());
                    orderDetails.setSalePrice(shoppingCar.getSalePrice());
                    orderDetails.setImage(shoppingCar.getImage());
                    orderAmount = orderAmount.add(orderDetails.getAmount());
                    orderDetailsService.save(orderDetails);
                }
                order.setAmount(orderAmount);//原价
                // 如果使用优惠券修改用户优惠券信息  计算订单金额
                if (StringUtils.isNotEmpty(order.getVoucherId())) {
                    UserCoupon userCoupon = new UserCoupon();
                    userCoupon.setId(order.getVoucherId());
                    userCoupon.setStatus("1");
                    userCoupon.setUseTime(new Date());
                    userCouponService.save(userCoupon);
                    // 获取优惠券信息
                    UserCoupon userCouponNow = userCouponService.get(order.getVoucherId());
                    order.setIsVoucher(2);// 使用优惠券
                    order.setVoucherPrice(userCouponNow.getCouponInfo().getAmount()); // 优惠券面值
                    order.setVoucherId(order.getVoucherId());// 用户优惠券ID
                    order.setSaleAmount(orderAmount.subtract(order.getVoucherPrice()));// 折扣价格
                } else {
                    //没有使用优惠券
                    order.setSaleAmount(orderAmount);
                    order.setIsVoucher(1);
                }
                // 支付金额
                order.setPayAmount(order.getSaleAmount());
                //是否保价在前端已做处理 1 不保价 2保价
                orderService.save(order);
                // 删除购物车
                shoppingCarService.deleteShoppingCarByIds(cartIds);
            } else {
                return R.fail("cartIds is null ");
            }
            //进行微信小程序支付
            return R.data(orderId);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 支付订单
     *
     * @param order 订单信息
     * @return
     */
    @PostMapping("/payOrder")
    public R payOrder(@RequestBody Order order) {
        try {
            order = orderService.get(order.getId());
            return wxPayService.payOrder(order);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取订单照片
     */
    @GetMapping("/getOrderImageList")
    public R getOrderImageList(OrderImage orderImage) {
        return R.data(orderImageService.findList(orderImage));
    }


    /**
     * 查询账户流水列表
     *
     * @param accountLog
     */
    @GetMapping("/getAccountLogList")
    public R<PageInfo> getAccountLogList(AccountLog accountLog, HttpServletRequest request,
            HttpServletResponse response) {
        accountLog.setPage(new PageDomain(request, response));
        return R.data(accountLogService.findPage(accountLog));
    }

    /**
     * 获取用户账所有户信息
     *
     * @param userInfoId
     * @return
     */
    @GetMapping("/getUserAccountInfo")
    public R getUserAccountInfo(@RequestParam String userInfoId) {
        UserInfo userInfo = userInfoService.get(userInfoId);
        if (null == userInfo) {
            return R.fail("用户不存在");
        }
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserInfoId(userInfo.getId());
        return R.data(accountInfoService.findList(accountInfo));
    }

    /**
     * 获取用户单个账户信息
     *
     * @param userInfoId
     * @param accountId
     * @return
     */
    @GetMapping("/getUserAccountInfoByAccountId")
    public R getUserAccountInfoByAccountId(@RequestParam String userInfoId, String accountId) {
        UserInfo userInfo = userInfoService.get(userInfoId);
        if (null == userInfo) {
            return R.fail("用户不存在");
        }
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserInfoId(userInfo.getId());
        accountInfo.setAccountId(accountId);
        List<AccountInfo> accountInfoList = accountInfoService.findList(accountInfo);
        if (accountInfoList.size() > 0) {
            accountInfo = accountInfoList.get(0);
            JSONArray jsonArray = JSONObject.parseArray(accountInfo.getAccountRuleRemark());
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                map.put(jsonObject.getString("type"), jsonObject);
            }
            accountInfo.setRuleMap(map);
            return R.data(accountInfo);
        } else {
            return R.fail("没有账户信息");
        }

    }

    /**
     * 通用上传请求
     *
     * @param file 文件流
     */
    @PostMapping("/userUpload")
    public R uploadFile(MultipartFile file) throws Exception {
        try {
            Map<String, Object> ajax = new HashMap<>();
            OSS ossClient = null;
            Company company = null;
            if (company == null) {
                company = new Company();
                company.setEndpoint("oss-cn-beijing.aliyuncs.com");
                company.setAliyunAccesssecret("uGojraJQGjtfqaujdrCHoGFdyT7YuU");
                company.setAliyunKey("LTAI4GKKBhZVzWJQfezgysgg");
                company.setBucketName("cn-system");
                company.setOssIsopen("1");
            }
            if ("1".equals(company.getOssIsopen())) {
                // 上传文件路径
                ossClient = new OSSClientBuilder().build(company.getEndpoint(), company.getAliyunKey(),
                        company.getAliyunAccesssecret());
                // 2: 获取文件上传的流
                InputStream inputStream = file.getInputStream();
                // 3：构建日期目录
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                String datePath = dateFormat.format(new Date());// 日期目录格式：2021/10/27

                // 4: 获取文件名
                String originname = file.getOriginalFilename();
                String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String filename = originname.substring(0, originname.lastIndexOf("."));
                String suffix = originname.substring(originname.lastIndexOf("."));
                String newName = filename + date + suffix;
                String fileUrl = datePath + "/" + newName;
                //5：文件上传到阿里云服务器
                ossClient.putObject(company.getBucketName(), fileUrl, inputStream);
                String url = "https://" + company.getBucketName() + "." + company.getEndpoint() + "/" + fileUrl;
                ajax.put("fileName", originname);
                ajax.put("url", url);
            } else {
                // 上传文件路径
                String filePath = AiDexConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + "/" + fileName;
                ajax.put("fileName", fileName);
                ajax.put("url", url);
            }
            return R.data(ajax);

        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 坐标转换
     *
     * @param lat
     * @param lng
     */
    @GetMapping("/getCityInfoByLatLng")
    public R getCityInfoByLatLng(@RequestParam String lat, @RequestParam String lng) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)) {
            map.put("isOk", "0");
            return R.data(map);
        }
        map = lbsMapService.getCityInfoByLatLng(lat, lng);
        return R.data(map);
    }


    /**
     * 查询用户订单列表
     *
     * @param userInfoId 用户ID
     * @param status     状态 洗护订单
     *                   -1待支付
     *                   0已支付，待入柜
     *                   1已入柜，待取走
     *                   2已取衣，送洗中
     *                   3已分拣 ，洗涤中
     *                   4已精洗 ，待分装
     *                   5已收纳，待配送
     *                   6 已到店，待取货
     *                   7已完成
     *                   9售后单
     *                   -99 取消订单
     *                   商城订单 -1待支付 0 已支付，待取货  1已完成 9售后单 -99 取消订单
     * @param orderType  订单类型 0 洗护订单 1 商城订单
     * @return
     */
    @GetMapping("/getUserOrderInfoList")
    public R<PageInfo<Order>> getUserOrderInfoList(@RequestParam String userInfoId, @RequestParam String status,
            @RequestParam String orderType) {
        Order order = new Order();
        order.setUserInfoId(userInfoId);
        order.setStatus(status);
        order.setOrderType(orderType);
        return R.data(orderService.findPageSelf(order));
    }

    /**
     * 查询订单详情
     *
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("/getOrderDetailsByIds")
    public R getOrderDetailsByIds(@RequestParam String orderId) {
        if (StringUtils.isNotEmpty(orderId)) {
            return R.data(orderService.get(orderId));
        } else {
            return R.fail("orderId is null");
        }

    }

    /**
     * 取消订单
     *
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("/cancelOrderInfo")
    public R cancelOrderInfo(@RequestParam String orderId) throws LopException {
        if (StringUtils.isNotEmpty(orderId)) {
            Order order = orderService.get(orderId);
            order.setStatus("-99");
            // 退款订单
            RefundOrder refundOrder = new RefundOrder();
            refundOrder.setOrderId(orderId);
            refundOrder.setStatus("0");// 待处理
            refundOrder.setRefundMoeny(order.getPayAmount());
            refundOrder.setOrderType(order.getOrderType());
            refundOrder.setId(orderId);
            refundOrder.setIsNewRecord();
            refundOrder.setUserInfoId(order.getUserInfoId());
            refundOrder.setRemark("用户取消订单");
            // 京东退单
            if(order.getCompanyId().equals(AiDexConfig.getCompanyId())){
                jdKuaiyunService.cancelJdKuaiYuanOrder(order);
            }
            return R.status(orderService.save(order) && refundOrderService.save(refundOrder));
        } else {
            return R.fail("orderId is null");
        }

    }

    /**
     * 查询退款订单
     *
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("/getRefundOrder")
    public R getRefundOrder(@RequestParam String orderId) {
        if (StringUtils.isNotEmpty(orderId)) {
            return R.data(refundOrderService.get(orderId));
        } else {
            return R.fail("orderId is null");
        }

    }

    /**
     * 扫码
     *
     * @param orderDetails 订单详情信息
     * @return
     */
    @PostMapping("/updateOrderDetailsQrCode")
    public R updateOrderDetailsQrCode(@RequestBody OrderDetails orderDetails) {
        if (StringUtils.isNotEmpty(orderDetails.getId())) {
            return R.data(orderDetailsService.get(orderDetails));
        } else {
            return R.fail("orderId is null");
        }

    }


    /**
     * 获取用户推广码
     *
     * @param userInfoId 当前用户ID
     * @return
     */

    @GetMapping("/getTuiJianQrCode")
    public R getTuiJianQrCode(@RequestParam String userInfoId) {
        UserInfo userInfo = userInfoService.get(userInfoId);
        Company company = companyService.get(userInfo.getCompanyId());
        if (null == company || null == userInfoId) {
            return R.data(null, "获取用户或者公司信息失败！");
        }
        weChatLoginService.setAppId(company.getWechatXappid(), company.getWechatXappSecret());
        return R.data(weChatLoginService.getUnlimitedQRCode("userInfoId=" + userInfoId, "pages/page/index"));
    }


    /**
     * 查询用户的推广人
     *
     * @param userInfoId 当前用户ID
     * @return
     */

    @GetMapping("/getTuiJianUserInfo")
    public R<PageInfo<UserInfo>> getTuiJianUserInfo(@RequestParam String userInfoId) {
        if (StringUtils.isEmpty(userInfoId)) {
            return R.data(null, "userInfoId为空");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserInfoId(userInfoId);
        return R.data(userInfoService.findPage(userInfo));
    }


    /**
     * 根据分类ID查询分类商品列表
     *
     * @param productInfo 分类ID
     * @return
     */

    @GetMapping("/getProductInfoList")
    public R<PageInfo<ProductInfo>> getProductInfoList(ProductInfo productInfo) {
        PageDomain page = productInfo.getPage();
        page.setPageSize(50);
        return R.data(productInfoService.findPage(productInfo));
    }

    /**
     * 根据产品ID查询商品详情
     *
     * @param id 产品ID
     * @return
     */

    @GetMapping("/getProductInfoDetails")
    public R<ProductInfo> getProductInfoDetails(@RequestParam String id) {
        return R.data(productInfoService.get(id));
    }

    /**
     * 获取字典类型参数
     *
     * @param type 字典类型
     * @return
     */

    @GetMapping("/getDictList")
    public R<List<SysDictData>> getDictList(@RequestParam String type) {
        return R.data(DictUtils.getDictList(type));
    }

    /**
     * 获取投递驿站列表
     *
     * @param lng
     * @param lat
     * @return 结果
     */
    @GetMapping("/getEquInfoList")
    public R getEquInfoList(@RequestParam String lng, String lat, HttpServletRequest request,
            HttpServletResponse response) {
        if (StringUtils.isEmpty(lng) || StringUtils.isEmpty(lat)) {
            return R.fail("未获取到定位信息");
        }
        EquInfo equInfo = new EquInfo();
        // equInfo.setCompanyId(companyId);
        equInfo.setStatus("0");
        equInfo.setPage(new PageDomain(request, response));
        equInfo.getPage().setPageSize(10000);
        PageInfo<EquInfo> pageInfo = equInfoService.getRedisEquInfoList(equInfo);
        // Map<String,String> latLng= lbsMapService.translateLatLng(lat,lng);
        List<EquInfo> list = new ArrayList<>();
        double setDistance=Double.parseDouble(sysDictDataService.selectDictValue("store_juli","distances"));
        for (EquInfo a : pageInfo.getList()) {
            double distance = DictanceUtil.getDistance(Double.valueOf(lng), Double.valueOf(lat),
                    Double.valueOf(a.getEquLng()), Double.valueOf(a.getEquLat()));
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);
            String distanceStr = format.format(distance);
            a.setDistance(distance+"");
            //范围
            if(distance<=setDistance){
                list.add(a);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size() - 1; j++) {
                if (Double.valueOf(list.get(i).getDistance()) < Double.valueOf(list.get(j).getDistance())) {
                    EquInfo e = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, e);
                }
            }
        }
        pageInfo.setList(list);
        pageInfo.setPageSize(list.size());
        return R.data(pageInfo);
    }


    /**
     * 获取新闻列表
     *
     * @return 结果
     */
    @ApiOperation(value = "用户端-获取新闻列表")
    @GetMapping("/getNewsList")
    public R getNewsList(@RequestParam String noticeType, HttpServletRequest request, HttpServletResponse response) {
        SysNotice notice = new SysNotice();
        notice.setNoticeType(noticeType);
        notice.setPage(new PageDomain(request, response));
        return R.data(sysNoticeService.findPage(notice));
    }

    /**
     * 获取新闻详情
     *
     * @return 结果
     */
    @ApiOperation(value = "用户端-获取新闻详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "分页信息（pageNum,pageSize）", required = true),
            @ApiImplicitParam(name = "pageSize", value = "分页信息（pageNum,pageSize）", required = true),
            @ApiImplicitParam(name = "noticeType", value = "类型（2:新闻 3:关于我们 4:帮助中心）", required = true)})
    @GetMapping("/getNewsDetails")
    public R getNewsDetails(@RequestParam String id) {
        return R.data(sysNoticeService.get(id));
    }


    /**
     * 小程序友情链接 （废弃）
     *
     * @param friendsLinks
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getFriendsLinkList")
    public R getFriendsLinkList(FriendsLinks friendsLinks, HttpServletRequest request, HttpServletResponse response,
            @RequestHeader(name = "company-id") String companyId) {
        friendsLinks.setCompanyId(companyId);
        // friendsLinks.setPage(new PageDomain(request, response));
        return R.data(friendsLinksService.findList(friendsLinks));
    }


    /**
     * 小程序分享链接点击数量累计（废弃）
     *
     * @param friendsLinks
     * @return
     */
    @PostMapping("/getClickFriendsLinkList")
    public R getClickFriendsLinkList(@RequestBody FriendsLinks friendsLinks) {
        friendsLinks = friendsLinksService.get(friendsLinks.getId());
        friendsLinks.setClicks(friendsLinks.getClicks() + 1);
        return R.data(friendsLinksService.save(friendsLinks));
    }

    /**
     * 查询首页滚动订单信息（废弃）
     */
    @GetMapping("/getOrderShowList")
    public R<PageInfo> getOrderShowList(Order order, HttpServletRequest request, HttpServletResponse response,
            @RequestHeader(name = "company-id") String companyId) {
        order.setPage(new PageDomain(request, response));
        order.setCompanyId(companyId);

        PageInfo<Order> pageInfoList = orderService.findPage(order);
        List<Order> list = new ArrayList<>();
        for (Order o : pageInfoList.getList()) {
            // 伍家岗   张*生，通过回收柜回收服务获得31.98元
            String areas = o.getUserInfo().getArea();
            String name = "";
            if (StringUtils.isEmpty(o.getUserInfo().getName())) {
                continue;
            }
            if (o.getUserInfo().getName().length() > 2) {
                name = o.getUserInfo().getName().substring(0, 1) + "*" + o.getUserInfo().getName().substring(2);
            } else {
                name = o.getUserInfo().getName().substring(0, 1) + "*";
            }
            if (StringUtils.isEmpty(areas) || StringUtils.isNull(areas)) {
                areas = "";
            }
            String text = areas + " " + name + " ，通过回收柜回收服务获得" + o.getAmount() + "元";
            list.add(o);
        }
        pageInfoList.setList(list);
        return R.data(pageInfoList);
    }


    /**
     * h5 登录用户授权链接
     *
     * @param companyId 公司ID
     * @return
     */
    @GetMapping("/getWxH5Auth2")
    public R getWxH5Auth2(@RequestHeader(name = "company-id") String companyId) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(companyId)) {
            return R.fail("companyId 参数为空");
        }
        Company company = companyService.get(companyId);
        return R.data(weChatLoginService.getWxH5Auth2(company.getWechatMpappid(), "snsapi_base",
                URLEncoder.encode(company.getRedirectUri(), "UTF-8"), companyId));
    }

    /**
     * 微信用户h5登录
     *
     * @param wxOauth2
     * @return
     */
    @PostMapping("/wxh5login")
    public R wxh5login(@RequestBody WxOauth2 wxOauth2, @RequestHeader(name = "company-id") String companyId) {
        Company company = companyService.get(companyId);
        if (null == company) {
            return R.fail("商户不存在");
        }
        if (!StringUtils.isEmpty(wxOauth2.getOpenId())) {
            return R.data(userInfoService.get(wxOauth2.getOpenId()));
        }
        if (!StringUtils.isEmpty(wxOauth2.getCode())) {
            UserInfo userInfo = new UserInfo();
            userInfo.setOpenid(weChatLoginService.getMpH5AccessToken(company.getWechatMpappid(),
                    company.getWechatMpappSecret(), wxOauth2.getCode()));
            userInfo.setCompanyId(companyId);
            return R.data(weChatLoginService.login(userInfo));
        }
        return null;
    }

    /**
     * 微信用户h5实名认证
     *
     * @param userInfo name phone idCard
     * @return
     */
    @PostMapping("/shiMingCertify")
    public R shiMingCertify(@RequestBody UserInfo userInfo, @RequestHeader(name = "company-id") String companyId) {
        Company company = companyService.get(companyId);
        if (null == company) {
            return R.fail("商户不存在");
        }
        if (StringUtils.isEmpty(userInfo.getId())) {
            return R.fail("id 为空");
        }
        // 介入阿里云实名认证接口
        if (AliyunUtils.verifyIdName(userInfo.getName(), userInfo.getIdCard()) == 1) {
            userInfo.setIsShiming(1);
            if (userInfoService.save(userInfo)) {
                return R.data(userInfoService.get(userInfo.getId()));
            } else {
                return R.fail("实名失败");
            }
        } else {
            return R.fail("姓名与身份证不一致");
        }
    }

    /**
     * 获取演出信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getSongInfo")
    public R getSongInfo(@RequestParam String id) {
        return R.data(songsInfoService.get(id));
    }

    /**
     * 用户领门票
     *
     * @param userSongsTicket userInfoId 用户ID
     * @param userSongsTicket songsTicketId 演出ID
     * @return
     */
    @PostMapping("/userGetSongTicket")
    public R userGetSongTicket(@RequestBody UserSongsTicket userSongsTicket) {
        if (userSongsTicketService.findList(userSongsTicket).size() > 0) {
            return R.fail("请勿重复领取门票");
        }
        userSongsTicket.setSort(userSongsTicketService.findMaxSort(userSongsTicket));
        userSongsTicket.setIsUse(0);
        userSongsTicket.setStatus("0");
        userSongsTicket.setUseCode(StringUtils.getRandomCharacterAndNumber(4));// 核销码
        SongsInfo songsInfo = songsInfoService.get(userSongsTicket.getSongsTicketId());
        if (songsInfo.getBeleft() == 0) {
            return R.fail("门票已经领完");
        }
        SongsInfo newSongInfo = new SongsInfo();
        newSongInfo.setId(songsInfo.getId());
//        if(StringUtils.isNull(songsInfo.getBeleft())){
        newSongInfo.setBeleft(songsInfo.getTotel() - 1);
//        }else {
        newSongInfo.setBeleft(songsInfo.getBeleft() - 1);
//        }
        newSongInfo.setVersion(songsInfo.getVersion());
        songsInfoService.save(newSongInfo);
        return R.data(userSongsTicketService.save(userSongsTicket));
    }

    /**
     * 用户的领门票列表
     *
     * @param userSongsTicket userInfoId 用户ID
     * @return
     */
    @GetMapping("/getUserSongTicketList")
    public R getUserSongTicketList(UserSongsTicket userSongsTicket) {
        return R.data(userSongsTicketService.findPage(userSongsTicket));
    }


    /**
     * 用户的领门票详情
     *
     * @param id 门票ID
     * @return
     */
    @GetMapping("/getUserSongTicketDetails")
    public R getUserSongTicketDetails(@RequestParam String id) {
        return R.data(userSongsTicketService.get(id));
    }


    /**
     * 订单上门时间获取
     * @return
     */
    @GetMapping("/getOrderToHomeTime")
    public R getOrderToHomeTime() {
        List<String> toDaysTimes = new ArrayList<>();
        List<String> tomorrowTimes = new ArrayList<>();
        List<String> acquiredTimes = new ArrayList<>();
        Map<String,String> days = new HashMap<>();
        Map<String, Object> returnMap = new HashMap<>();
        int nowTime=Integer.parseInt(DateFormatUtils.format(new Date(),"HH"));
        // 添加日期 今天日
        days.put("toDay",DateFormatUtils.format(new Date(), "MM-dd"));
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        days.put("tomorrow",DateFormatUtils.format(calendar.getTime(), "MM-dd"));
        // 将日期增加1天
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        days.put("acquired",DateFormatUtils.format(calendar.getTime(), "MM-dd"));
        // 添加时间段
        for(int i=9;i<=19;i++){
            tomorrowTimes.add((i)+":00-"+(i+1)+":00");
            acquiredTimes.add((i)+":00-"+(i+1)+":00");
        }
        if(nowTime<9){
            for(int i=9;i<=19;i++){
                toDaysTimes.add((i)+":00-"+(i+1)+":00");
            }
        }else{
            for(int i=nowTime;i<19;i++){
                if(nowTime<19){
                    toDaysTimes.add(i+1+":00-"+(i+2)+":00");
                }
            }
        }

        returnMap.put("toDaysTimes", toDaysTimes);
        returnMap.put("tomorrowTimes", tomorrowTimes);
        returnMap.put("acquiredTimes", acquiredTimes);
        returnMap.put("days", days);
        return R.data(returnMap);
    }

    public static void main(String[] args) {
        List<String> toDaysTimes = new ArrayList<>();
        List<String> tomorrowTimes = new ArrayList<>();
        List<String> acquiredTimes = new ArrayList<>();
        Map<String,String> days = new HashMap<>();
        Map<String, Object> returnMap = new HashMap<>();
        int nowTime=19;
                // Integer.parseInt(DateFormatUtils.format(new Date(),"HH"));
        // 添加日期 今天日
        if(nowTime<19){
            days.put("toDay",DateFormatUtils.format(new Date(), "MM-dd"));
        }
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        days.put("tomorrow",DateFormatUtils.format(calendar.getTime(), "MM-dd"));
        // 将日期增加1天
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        days.put("acquired",DateFormatUtils.format(calendar.getTime(), "MM-dd"));
        // 添加时间段
        for(int i=9;i<=19;i++){
            tomorrowTimes.add((i)+":00-"+(i+1)+":00");
            acquiredTimes.add((i)+":00-"+(i+1)+":00");
        }
        if(nowTime<9){
            for(int i=9;i<=19;i++){
                toDaysTimes.add((i)+":00-"+(i+1)+":00");
            }
        }else{
            for(int i=nowTime;i<19;i++){
                if(nowTime<19){
                    toDaysTimes.add(i+1+":00-"+(i+2)+":00");
                }
            }
        }

        returnMap.put("toDaysTimes", toDaysTimes);
        returnMap.put("tomorrowTimes", tomorrowTimes);
        returnMap.put("acquiredTimes", acquiredTimes);
        returnMap.put("days", days);
        System.out.println(returnMap);
    }


    /**
     * 获取公司信息
     *
     * @param companyId 当前用户ID
     * @return
     */

    @GetMapping("/getCompanyInfo")
    public R getCompanyInfo(@RequestParam String companyId) {
        return R.data(companyService.getRedisCompany(companyId));
    }

}
